package com.kiseny.main;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

import com.common.fileFilter.JpgFileFilter;
import com.common.fileFilter.NotSVNFileFilter;
import com.common.fileFilter.TxtFileFilter;
import com.common.util.Constants;


public class UploadToDHGate {
	
	private static final String URL_MAIN = "http://seller.dhgate.com/";
	private static final String dataPath = "D:/svn2/morgan0329/doc2/yunbei/";
	private static final String destFileName = "D:/svn2/shop2011/doc/dest.properties";
	private static final String uploadTool = "D:/svn2/shop2011/exe/uploadDHEN.exe";
	private static final int INTERVAL_TIME = 4000;

	public static void main(String[] args) throws Exception {

		Properties prop = new Properties();
		prop.load(new FileReader(destFileName));

		WebDriver driver = new InternetExplorerDriver();

		// step0: Login to DHAgete
		driver.get(URL_MAIN + "mydhgate/index.do");
		
		WebElement loginForm = driver.findElement(By.id("signinActionForm"));
		loginForm.findElement(By.id("username")).sendKeys("kiseny");
		Thread.sleep(2 * INTERVAL_TIME);
		driver.findElement(By.name("login")).click();

		// step1: Go to upload page.
		File rootFile = new File(dataPath);
		File[] folders = rootFile.listFiles(new NotSVNFileFilter());
		Properties prop2 = new Properties();
		for (File folder : folders) {
			if (folder.isDirectory()) {

				File[] txtFiles = folder.listFiles(new TxtFileFilter());
				File[] jpgFiles = folder.listFiles(new JpgFileFilter());

				for (File file : txtFiles) {

					prop2.clear();
					prop2.load(new FileReader(file));

					driver.get(URL_MAIN + "mydhgate/product/productentry.do?act=catalogload&catalogid=174508&type=0");
		
					//Product Name
					driver.findElement(By.id("productname")).sendKeys(getProductName(prop2));
					
					
					//Specifications
					driver.findElement(By.id("productdesc")).sendKeys(getSpecifications(prop2));
					
					
					//Upload picture
					List<WebElement> uploadButtons = driver.findElement(By.id("div_addpic_btn")).findElements(By.tagName("button"));
					uploadButtons.get(1).click();
					WebElement uploadForm = driver.findElement(By.id("uploadpicModalContent"));
					WebElement uploadButtonInForm = uploadForm.findElement(By.className("s-margin2")).findElements(By.tagName("span")).get(0);

		 	        List<File> jpgFileList = new ArrayList<File>();
		 	        for (File jpgFile : jpgFiles) {
		 	        	if(jpgFile.getName().startsWith((String) prop2.get("ProductCode"))) {
		 	        		jpgFileList.add(jpgFile);
		 	        	}
		 	        }
		 	        
		 	        int totalPicNum = jpgFileList.size() <= 4 ? jpgFileList.size() : 4;
		 	        if (totalPicNum == 0) {
		 	        	file.delete();
		 	        	continue;
		 	        }
		 	        for(int i=0; i< totalPicNum; i++) {
						try {
							Runtime.getRuntime().exec(uploadTool + " " + folder.getPath() + "\\" 
                                + (String) prop2.get("ProductCode") + Constants.MARKS_DASH + i + ".jpg");
							uploadButtonInForm.click();
                            Thread.sleep(2 * INTERVAL_TIME);
						} catch (Exception e) {
							e.printStackTrace();
						}
		 	        }
		 	       List<WebElement> saveButtons = uploadForm.findElements(By.tagName("button"));
		 	       saveButtons.get(4).click();
		 	      
		 	       
					//Details
		 	        WebElement detailsSelect = driver.findElement(By.id("sel_featureshtmlmodel"));
		 	        List<WebElement> detailsSelectOptions = detailsSelect.findElements(By.tagName("option"));
		 	        for (WebElement detailsSelectOption : detailsSelectOptions) {
		 	         if (detailsSelectOption.getAttribute("value").equals("86C69D17F12DF3BFE0400A0AD40A2CA1")) {
		 	        	detailsSelectOption.setSelected();
		 	         }
		 	        }
		 	        WebElement pAgreementDIV = driver.findElement(By.id("p_agreement"));
		 	        Thread.sleep(3 * INTERVAL_TIME);
		 	        List<WebElement> ps = pAgreementDIV.findElements(By.tagName("p"));
		 	       
					ps.get(1).click();
					ps.get(1).sendKeys(getDetails(prop2));
					ps.get(4).click();
					ps.get(4).sendKeys("15");
					
					driver.findElement(By.id("div_htmltemp")).findElement(By.tagName("button")).click();
					
					
					// Service Confirmation
					WebElement confirmDiv = driver.findElement(By.id("sel_promisehtmlmodel"));
					confirmDiv.click();
					Thread.sleep(INTERVAL_TIME);

					List<WebElement> lis = driver.findElement(By.id("promise_list")).findElements(By.tagName("li"));
					lis.get(1).click();
					List<WebElement> confirmButtons = driver.findElement(
							By.id("modalContainer")).findElements(By.tagName("button"));
					confirmButtons.get(0).click();

					List<WebElement> fourTables = driver.findElements(By.className("syi_table_form"));


					//Table 2: Product Sell Information: first part.
					driver.findElement(By.id("sortbyradio2")).click();
					sendValue(driver.findElement(By.id("packquantity")), "5");
					fillPrice(driver, prop2);
					
					driver.findElement(By.id("productweight")).sendKeys(getPackageWeight(prop2));
					//Hard code here temporarily.
					driver.findElement(By.id("sizelen")).sendKeys("25");
					driver.findElement(By.id("sizewidth")).sendKeys("10");
					driver.findElement(By.id("sizeheight")).sendKeys("8");

					driver.findElement(By.id("div_EMS_myd")).getTagName();
					//Table 3: Product Sell Information: second part.
					driver.findElement(By.id("div_EMS_myd")).findElement(By.name("radio_EMS_discount")).click();
					driver.findElement(By.id("cb_EMS_mydiscount")).click();
					sendValue(driver.findElement(By.id("inp_EMS_mydiscount")), "0.6");

					
					//Table 4: Other Informations. 
					//1. validation Time is default one. 
					//2. no factory.
					//3. the product code is provided in our txt file.
					List<WebElement> itemsInTable4 = fourTables.get(3).findElements(By.className("td_1"));
					itemsInTable4.get(2).findElement(By.tagName("input")).sendKeys((String) prop2.get("ProductCode"));

					//Click Submit Button.
					System.out.println("********************Finished********************");
					file.delete();
					driver.findElement(By.id("btn_submitproduct")).click();
				}
			} else {
				// Empty
			}
		}
	}
	
	private static String getProductName(Properties prop) {
		String pn = null;
		String productName = (String) prop.get("ProductName");
		
		if (StringUtils.isNotBlank(productName)) {
			pn = productName;
		} else {
			String productNameEN = (String) prop.get("ProductNameEN");
			if (StringUtils.isNotBlank(productNameEN)) {
				pn = productNameEN;
			}
		}
		
		if (pn == null) {
			pn = "Product Name - Default";
		}
		
		return pn.replace("Yun Pui","Kiseny");
	}
	
	private static String getSpecifications(Properties prop) {
		
		StringBuffer specSB = new StringBuffer();
		
		String specifications = (String) prop.get("Specifications");
		String material = (String) prop.get("Material");
		if (StringUtils.isNotBlank(specifications) || StringUtils.isNotBlank(material)) {
			if(StringUtils.isNotBlank(specifications)) {
				specSB.append("Specifications: " + specifications + "\n");
			}
			if(StringUtils.isNotBlank(material)) {
				specSB.append("Material: " + material + "\n");
			}

		} else {
			String specificationsEN = (String) prop.get("SpecificationsEN");
			if (StringUtils.isNotBlank(specificationsEN)) {
				specSB.append("Specifications: " + specificationsEN + "\n");
			}
			String materialEN = (String) prop.get("MaterialEN");
			if (StringUtils.isNotBlank(materialEN)) {
				specSB.append("Material: " + materialEN + "\n");
			}
			String sizeEN = (String) prop.get("SizeEN");
			if (StringUtils.isNotBlank(sizeEN)) {
				specSB.append("Size: " + sizeEN + "\n");
			}
		}
		
		String spec = specSB.toString();
		if (spec.length() == 0) {
			spec = "Sorry, we forget to provide speicification.";
		} else {
			spec.substring(0, spec.length()-3);
		}
		
		return spec;
	}
	
	/**
	 * 1-2
	 * 3-10
	 * 10-30
	 * 31-100
	 * 101-199
	*/
	private static void fillPrice(WebDriver driver, Properties prop) {

		sendValue(driver.findElement(By.id("buyleast11")), "1");
		sendValue(driver.findElement(By.id("buymost11")), "2");
		sendValue(driver.findElement(By.id("supplierprice11")), ((String) prop.get("1-2")).replace("USD", ""));
		sendValue(driver.findElement(By.id("postday11")), "15"); //Post Days: 15.
		
		driver.findElement(By.id("divaddbutton1")).findElement(By.tagName("button")).click();
		sendValue(driver.findElement(By.id("buymost12")), "10");
		sendValue(driver.findElement(By.id("supplierprice12")), ((String) prop.get("3-10")).replace("USD", ""));
		sendValue(driver.findElement(By.id("postday12")), "15"); //Post Days: 15.
		
		driver.findElement(By.id("divaddbutton1")).findElement(By.tagName("button")).click();
		sendValue(driver.findElement(By.id("buymost13")), "30");
		sendValue(driver.findElement(By.id("supplierprice13")), ((String) prop.get("11-30")).replace("USD", ""));
		sendValue(driver.findElement(By.id("postday13")), "15"); //Post Days: 15.
		
		driver.findElement(By.id("divaddbutton1")).findElement(By.tagName("button")).click();
		sendValue(driver.findElement(By.id("buymost14")), "100");
		sendValue(driver.findElement(By.id("supplierprice14")), ((String) prop.get("31-100")).replace("USD", ""));
		sendValue(driver.findElement(By.id("postday14")), "15"); //Post Days: 15.
		
		driver.findElement(By.id("divaddbutton1")).findElement(By.tagName("button")).click();
		sendValue(driver.findElement(By.id("buymost15")), "199");
		sendValue(driver.findElement(By.id("supplierprice15")), ((String) prop.get("101-199")).replace("USD", ""));
		sendValue(driver.findElement(By.id("postday15")), "15"); //Post Days: 15.

	}
	
	private static void sendValue(WebElement webElment, String string) {
		webElment.clear();
		webElment.sendKeys(string);
	}
	
	private static String getPackageWeight(Properties prop) {
		if (prop.getProperty("PackageWeight") != null) {
			return((String) prop.getProperty("PackageWeight")).replace("Kilograms", "");
		} else {
			return "0.5";
		}
	}
	
	private static String getDetails(Properties prop) {
		StringBuffer sb = new StringBuffer();
		
		if (prop.get("DetailsEN") != null) {
			sb.append(((String) prop.get("DetailsEN")).replace(" BLANK ", "\n")
					.replace("BLANK ", "\n").replace("BLANK", " "));
		} else {
			sb.append("Product Details Description - Default\n");
		}
		return sb.toString();
	}
}